<?php

namespace SunAdmin\Service\FileSystem;

use SunAdmin\Model\AttachmentModel;
use think\Response;

class Download extends FilesystemBase
{
    /**
     * 通过附件ID下载文件
     */
    public function downloadById(int $attachmentId): Response
    {
        $attachment = AttachmentModel::find($attachmentId);
        if (!$attachment) {
            throw new \Exception("附件记录不存在");
        }

        // 如果磁盘不匹配，重新初始化
        if ($attachment->disk !== $this->currentDisk) {
            $this->initFilesystem($attachment->disk);
        }

        return $this->filesystem->download($attachment->path, $attachment->name);
    }

    /**
     * 通过文件路径下载文件
     */
    public function downloadByPath(string $filePath, ?string $fileName = null): Response
    {
        if (!$this->filesystem->exists($filePath)) {
            throw new \Exception("文件不存在");
        }

        return $this->filesystem->download($filePath, $fileName);
    }

    /**
     * 获取文件内容
     */
    public function getContent(string $filePath): string
    {
        if (!$this->filesystem->exists($filePath)) {
            throw new \Exception("文件不存在");
        }

        return $this->filesystem->get($filePath);
    }

    /**
     * 获取文件URL
     */
    public function getUrl(string $filePath): string
    {
        return $this->filesystem->url($filePath);
    }

    /**
     * 获取文件信息
     */
    public function getFileInfo(string $filePath): array
    {
        if (!$this->filesystem->exists($filePath)) {
            throw new \Exception("文件不存在");
        }

        return [
            'path' => $filePath,
            'url' => $this->filesystem->url($filePath),
            'size' => $this->filesystem->size($filePath),
            'mime_type' => $this->filesystem->mimeType($filePath),
            'last_modified' => $this->filesystem->lastModified($filePath),
            'disk' => $this->currentDisk
        ];
    }
} 